package com.example.service.impl;

import com.example.mapper.AuthorMapper;
import com.example.mapper.BookMenuMapper;
import com.example.mapper.BookMenuPreservationMapper;
import com.example.mapper.LabelMapper;
import com.example.pojo.*;
import com.example.service.BookMenuService;
import com.example.utils.ExcelUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BookMenuServiceImpl implements BookMenuService {

    @Autowired
    private BookMenuMapper bookMenuMapper;

    @Autowired
    private BookMenuPreservationMapper bookMenuPreservationMapper;

    @Autowired
    private LabelMapper labelMapper;

    @Autowired
    private AuthorMapper authorMapper;

    private List<BookMenu> addList;
    private List<BookMenu> updateList;
    private List<BookMenu> updateImgList;
    private List<BookMenu> notUpdateList;
    private List<BookMenu> multipleList;
    private int countName;
    private int countPrice;
    private int countPublisher;
    private int countPublishTime;
    private int countAuthor;
    private int countType;
    private List<Label> labelList;

    @Override
    public String addOrUpdateBookMenu(String originalPath) {
        List<BookMenu> bookMenuList = ExcelUtils.readExcel(originalPath, BookMenu.class);
        if(bookMenuList==null){
            return "文件不存在";
        }
        List<BookMenu> allAddList=new ArrayList<>();
        List<BookMenu> allUpdateList=new ArrayList<>();
        List<BookMenu> allUpdateImgList=new ArrayList<>();
        List<BookMenu> allNotUpdateList=new ArrayList<>();
        List<BookMenu> allMultipleList=new ArrayList<>();
        int allCountName=0;
        int allCountPrice=0;
        int allCountPublisher=0;
        int allCountPublishTime=0;
        int allCountAuthor=0;
        int allCountType=0;
        List<BookMenu> temporaryList=new ArrayList<>();
        //获得当前代理对象
        BookMenuServiceImpl proxy = (BookMenuServiceImpl) AopContext.currentProxy();
        try {
            for (int i=0;i<bookMenuList.size();i++) {
                BookMenu bookMenu=bookMenuList.get(i);
                if(bookMenu.getPrice()==null||bookMenu.getIsbn()==null){
                    continue;
                }
                temporaryList.add(bookMenu);
                if(temporaryList.size()%2000==0||i==bookMenuList.size()-1){
                    proxy.addOrUpdateData(temporaryList);
                    temporaryList.clear();

                    allAddList.addAll(addList);
                    allUpdateList.addAll(updateList);
                    allUpdateImgList.addAll(updateImgList);
                    allNotUpdateList.addAll(notUpdateList);
                    allMultipleList.addAll(multipleList);
                    allCountName+=countName;
                    allCountPrice+=countPrice;
                    allCountPublisher+=countPublisher;
                    allCountPublishTime+=countPublishTime;
                    allCountAuthor+=countAuthor;
                    allCountType+=countType;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("更新名字："+allCountName);
        System.out.println("更新价格："+allCountPrice);
        System.out.println("更新出版社："+allCountPublisher);
        System.out.println("更新出版时间："+allCountPublishTime);
        System.out.println("更新作者："+allCountAuthor);
        System.out.println("更新标签："+allCountType);
        ExcelUtils.writeExcel(originalPath.substring(0,originalPath.indexOf("."))+"-增加"+".xlsx",allAddList, BookMenu.class);
        ExcelUtils.writeExcel(originalPath.substring(0,originalPath.indexOf("."))+"-更新"+".xlsx",allUpdateList, BookMenu.class);
        ExcelUtils.writeExcel(originalPath.substring(0,originalPath.indexOf("."))+"-更新图片"+".xlsx",allUpdateImgList, BookMenu.class);
        ExcelUtils.writeExcel(originalPath.substring(0,originalPath.indexOf("."))+"-没更新"+".xlsx",allNotUpdateList, BookMenu.class);
        ExcelUtils.writeExcel(originalPath.substring(0,originalPath.indexOf("."))+"-有多个"+".xlsx",allMultipleList, BookMenu.class);
        return "成功（增加："+allAddList.size()+"，更新："+allUpdateList.size()+"，更新图片："+allUpdateImgList.size()+"，没更新："+allNotUpdateList.size()+"，有多个："+allMultipleList.size()+"）";
    }

    @Transactional
    public void addOrUpdateData(List<BookMenu> bookMenuList){
        addList=new ArrayList<>();
        updateList=new ArrayList<>();
        updateImgList=new ArrayList<>();
        notUpdateList=new ArrayList<>();
        multipleList=new ArrayList<>();
        Map<Integer,BookMenu> map=new HashMap<>();
        countName=0;
        countPrice=0;
        countPublisher=0;
        countPublishTime=0;
        countAuthor=0;
        countType=0;
        for (BookMenu bookMenu : bookMenuList) {
            List<BookMenu> bookMenus = bookMenuMapper.selectByIsbnAndPriceRange(bookMenu.getIsbn(),bookMenu.getPrice());
            if(bookMenus.isEmpty()){
                bookMenuMapper.insert(bookMenu);
                addList.add(bookMenu);
            }else if(bookMenus.size()==1){
                int i=0;
                int j=0;
                int k=0;
                BookMenu bookMenu1 = bookMenus.get(0);
                BookMenu bookMenu2=map.get(bookMenu1.getId());
                if(bookMenu2!=null){
                    bookMenu1=bookMenu2;
                }
                if((bookMenu1.getName()==null|| bookMenu1.getName().isEmpty())&&bookMenu.getName()!=null){
                    bookMenu1.setName(bookMenu.getName());
                    i=1;
                    countName++;
                }
                //查找到一条记录的话，价格肯定不为空
                if(bookMenu1.getPrice()==0.00&&bookMenu.getPrice()!=null&&bookMenu.getPrice()!=0.00){
                    bookMenu1.setPrice(bookMenu.getPrice());
                    j=1;
                    countPrice++;
                }
                if((bookMenu1.getPublisher()==null|| bookMenu1.getPublisher().isEmpty())&&bookMenu.getPublisher()!=null){
                    bookMenu1.setPublisher(bookMenu.getPublisher());
                    i=1;
                    countPublisher++;
                }
                if((bookMenu1.getImg()==null|| bookMenu1.getImg().isEmpty())&&bookMenu.getImg()!=null){
                    bookMenu1.setImg(bookMenu.getImg());
                    k=1;
                }
                if((bookMenu1.getContentValidity()==null|| bookMenu1.getContentValidity().isEmpty())&&bookMenu.getContentValidity()!=null){
                    bookMenu1.setContentValidity(bookMenu.getContentValidity());
                    i=1;
                }
                if((bookMenu1.getPublishTime()==null|| bookMenu1.getPublishTime().isEmpty())&&bookMenu.getPublishTime()!=null){
                    bookMenu1.setPublishTime(bookMenu.getPublishTime());
                    i=1;
                    countPublishTime++;
                }
                if((bookMenu1.getAuthor()==null|| bookMenu1.getAuthor().isEmpty())&&bookMenu.getAuthor()!=null){
                    bookMenu1.setAuthor(bookMenu.getAuthor());
                    i=1;
                    countAuthor++;
                }
                if((bookMenu1.getTranslator()==null|| bookMenu1.getTranslator().isEmpty())&&bookMenu.getTranslator()!=null){
                    bookMenu1.setTranslator(bookMenu.getTranslator());
                    i=1;
                }
                if((bookMenu1.getType()==null|| bookMenu1.getType().isEmpty())&&bookMenu.getType()!=null){
                    bookMenu1.setType(bookMenu.getType());
                    i=1;
                    countType++;
                }
                if((i==1||k==1)&&j==0){
                    map.put(bookMenu1.getId(),bookMenu1);
                    if(map.size()%1000==0){
                        bookMenuMapper.batchUpdate(map.values());
                        map.clear();
                    }
                    updateList.add(bookMenu);
                    if(k==1){
                        updateImgList.add(bookMenu);
                    }
                }else if(j==1){
                    //更新到价格，立马更新，不要影响后面查询
                    bookMenuMapper.update(bookMenu1);
                    map.remove(bookMenu1.getId());
                    updateList.add(bookMenu);
                    if(k==1){
                        updateImgList.add(bookMenu);
                    }
                }else{
                    notUpdateList.add(bookMenu);
                }
            }else {
                multipleList.add(bookMenu);
            }
        }
        if(map.size()>=1){
            bookMenuMapper.batchUpdate(map.values());
        }
    }

    @Override
    public String downloadImage(String originalPath){
        List<BookMenu> bookMenuList = ExcelUtils.readExcel(originalPath, BookMenu.class);
        if(bookMenuList==null){
            return "文件不存在";
        }
        int count=0;
        int num=-1;  //控制抛SocketException时就重试一次，再不行就放弃
        int batchNum=0;
        String downloadImageDir;
        for (; ; ) {
            downloadImageDir=originalPath.substring(0,originalPath.indexOf("."))+"-下载图片"+ ++batchNum +"/";
            File dirFile = new File(downloadImageDir);
            if(!dirFile.exists()){
                break;
            }
        }
        List<BookMenu> fileNotFoundList=new ArrayList<>();
        for (int i=0;i<bookMenuList.size();i++) {
            num++;
            BookMenu bookMenu=bookMenuList.get(i);
            String imageUrl=bookMenu.getImg();
            if(imageUrl==null){
                continue;
            }
            InputStream inputStream=null;
            OutputStream outputStream=null;
            try {
                //获取图片输入流
                URL url = new URL(imageUrl);
                inputStream = url.openStream();
                //目录不存在则创建目录
                File file = new File(downloadImageDir);
                if(!file.exists()){
                    boolean b = file.mkdir();
                    if(!b){
                        return "下载图片目录创建失败";
                    }
                }
                String downloadImagePath=downloadImageDir+imageUrl.substring(imageUrl.lastIndexOf('/')+1);
                outputStream=new FileOutputStream(downloadImagePath);
                byte[] buffer=new byte[1024];
                int len;
                while ((len=inputStream.read(buffer))!=-1){
                    outputStream.write(buffer,0,len);
                }
                count++;
                num=i;
            } catch (FileNotFoundException e) {
                fileNotFoundList.add(bookMenu);
                num=i;
            } catch (SocketException e){
                if(num==i){
                    i--;
                }else {
                    num=i;
                }
                System.out.println("抛出SocketException异常："+imageUrl);
            } catch (Exception e){
                System.out.println("抛出其它异常："+imageUrl);
                num=i;
            }
            finally {
                try {
                    if(inputStream!=null)inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                try {
                    if(outputStream!=null)outputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                if((i+1)%10000==0){
                    System.out.println(count);
                    ExcelUtils.writeExcel(originalPath,fileNotFoundList, BookMenu.class);
                    fileNotFoundList.clear();
                    System.out.println("----------------------------------------------"+batchNum+"----------------------------------------------");
                    for (; ; ) {
                        downloadImageDir=originalPath.substring(0,originalPath.indexOf("."))+"-下载图片"+ ++batchNum +"/";
                        File dirFile = new File(downloadImageDir);
                        if(!dirFile.exists()){
                            break;
                        }
                    }
                }
            }
        }
        ExcelUtils.writeExcel(originalPath,fileNotFoundList, BookMenu.class);
        return "成功（下载图片："+count+"张）";
    }

    @Override
    public String countBookExistNum(String originalPath) {
        List<BookMenu> bookMenuList = ExcelUtils.readExcel(originalPath, BookMenu.class);
        if(bookMenuList==null){
            return "文件不存在";
        }
        List<BookMenu> existBookList=new ArrayList<>();
        List<BookMenu> noExistBookList=new ArrayList<>();
        List<BookMenu> existBookDatabaseList=new ArrayList<>();
        for (BookMenu bookMenu : bookMenuList) {
            List<BookMenu> bookMenus = bookMenuMapper.selectByIsbn(bookMenu.getIsbn());
            if(bookMenus.size()>0){
                BookMenu bookMenu1=bookMenus.get(0);
                for (BookMenu menu : bookMenus) {
                    if(menu.getPrice()>bookMenu1.getPrice()){
                        bookMenu1=menu;
                    }
                }
                //填充保值率
                BookMenuPreservation bookMenuPreservation = bookMenuPreservationMapper.selectByBookId(bookMenu1.getId());
                bookMenu1.setPreservation(bookMenuPreservation.getPreservation());
                existBookDatabaseList.add(bookMenu1);
                existBookList.add(bookMenu);
            }else {
                noExistBookList.add(bookMenu);
            }
        }
        ExcelUtils.writeExcel(originalPath.substring(0,originalPath.indexOf("."))+"-存在"+".xlsx",existBookList, BookMenu.class);
        ExcelUtils.writeExcel(originalPath.substring(0,originalPath.indexOf("."))+"-数据库中"+".xlsx",existBookDatabaseList, BookMenu.class);
        ExcelUtils.writeExcel(originalPath.substring(0,originalPath.indexOf("."))+"-不存在"+".xlsx",noExistBookList, BookMenu.class);
        return "成功（存在："+existBookList.size()+"，不存在："+noExistBookList.size()+"）";
    }

    @Override
    public String exhaustionIsbn(String originalPath) {
        List<BookMenu> bookMenuList = ExcelUtils.readExcel(originalPath, BookMenu.class);
        if(bookMenuList==null){
            return "文件不存在";
        }
        for (BookMenu bookMenu : bookMenuList) {
            if(bookMenu.getIsbn()==null||bookMenu.getPublisher()==null){
                continue;
            }
            String[] split = bookMenu.getIsbn().split("-");
            List<BookMenu> bookMenuList1 = bookMenuMapper.selectByPublisherPrefix(bookMenu.getPublisher());
            if(bookMenuList1==null||bookMenuList1.isEmpty()){
                System.out.println(bookMenu.getPublisher()+"：无数据");
                continue;
            }
            List<Map<String,String>> mapList=new ArrayList<>();
            for (BookMenu bookMenu1 : bookMenuList1) {
                if(bookMenu1.getIsbn().length() < 4+split[1].length()){
                    continue;
                }
                Map<String,String> map=new HashMap<>();
                map.put("haoduan",bookMenu1.getIsbn().substring(4,4+split[1].length()));
                if(split[1].length()==2){
                    map.put("first",bookMenu1.getIsbn().substring(6,7));
                    map.put("second",bookMenu1.getIsbn().substring(7,8));
                }else if(split[1].length()==3){
                    map.put("first",bookMenu1.getIsbn().substring(7,8));
                }
                mapList.add(map);
            }
            Map<String, List<Map<String, String>>> haoduanMap = mapList.stream().collect(Collectors.groupingBy(map -> map.get("haoduan")));
            //找出量级最长的
            int masterLength = 0;
            for (String key : haoduanMap.keySet()) {
                if(masterLength==0){
                    masterLength=String.valueOf(haoduanMap.get(key).size()).length();
                    continue;
                }
                if(String.valueOf(haoduanMap.get(key).size()).length()>masterLength){
                    masterLength=String.valueOf(haoduanMap.get(key).size()).length();
                }
            }
            //获取需要的号段
            Map<String, List<Map<String, String>>> requireHaoduanMap = new HashMap<>();
            for (String key : haoduanMap.keySet()) {
                if(String.valueOf(haoduanMap.get(key).size()).length()==masterLength  //和主要号段在一个量级就是需要的号段
                        ||((split[1].length()==4||split[1].length()==5)&&haoduanMap.get(key).size()>=100)){  //四、五位数的，上百本的号段是需要的号段
                    requireHaoduanMap.put(key,haoduanMap.get(key));
                }
            }
            //获取号段后的第一位或第二位
            Map<String,List<String>> requireMap = new HashMap<>();
            for (String haoduanKey : requireHaoduanMap.keySet()) {
                List<Map<String, String>> mapList1 = requireHaoduanMap.get(haoduanKey);
                List<String> requireList = new ArrayList<>();
                if(split[1].length()==2){
                    Map<String, List<Map<String, String>>> firstMap = mapList1.stream().collect(Collectors.groupingBy(map -> map.get("first")));
                    for (String firstKey : firstMap.keySet()) {
                        List<Map<String, String>> mapList2 = firstMap.get(firstKey);
                        if(mapList2.size()/100000.0<0.01){
                            continue;
                        }
                        Map<String, List<Map<String, String>>> secondMap = mapList2.stream().collect(Collectors.groupingBy(map -> map.get("second")));
                        for (String secondKey : secondMap.keySet()) {
                            if(secondMap.get(secondKey).size()/10000.0>=0.01){
                                requireList.add(firstKey+secondKey);
                            }
                        }
                    }
                }else if(split[1].length()==3){
                    Map<String, List<Map<String, String>>> firstMap = mapList1.stream().collect(Collectors.groupingBy(map -> map.get("first")));
                    for (String firstKey : firstMap.keySet()) {
                        List<Map<String, String>> mapList2 = firstMap.get(firstKey);
                        if (mapList2.size() / 10000.0 >= 0.01) {
                            requireList.add(firstKey);
                        }
                    }
                }
                requireMap.put(haoduanKey,requireList);
            }
            //拼接12位isbn
            List<String> isbnList12=new ArrayList<>();
            List<String> rangeList=new ArrayList<>();
            for (String haoduanKey : requireMap.keySet()) {
                List<String> list = requireMap.get(haoduanKey);
                if(list.isEmpty()){
                    if(split[1].length()==4||split[1].length()==5){  //四位数和五位数的全覆盖
                        int n= (int) Math.pow(10,8-split[1].length());
                        String isbnPrefix="9787"+haoduanKey+"0".repeat(8-split[1].length());
                        rangeList.add(isbnPrefix);
                        for (int i = 0; i < n; i++) {
                            isbnList12.add(String.valueOf(Long.parseLong(isbnPrefix)+i));
                        }
                        rangeList.add(isbnList12.get(isbnList12.size()-1));
                    }
                    continue;
                }
                Collections.sort(list);
                String minIsbn=null;
                for (String s : list) {
                    String isbnPrefix="9787"+haoduanKey+s;
                    if(minIsbn==null){
                        for (BookMenu bookMenu1 : bookMenuList1) {
                            if(bookMenu1.getIsbn().startsWith(isbnPrefix)){
                                minIsbn=bookMenu1.getIsbn();
                                break;
                            }
                        }
                        rangeList.add(minIsbn.substring(0,minIsbn.length()-1));
                        int startNum = Integer.parseInt(minIsbn.substring(8, minIsbn.length() - 1));
                        for (int i = startNum; i < 10000; i++) {
                            isbnList12.add(String.valueOf(Long.parseLong(isbnPrefix+"0000")+i));
                        }
                        continue;
                    }
                    for (int i = 0; i < 10000; i++) {
                        isbnList12.add(String.valueOf(Long.parseLong(isbnPrefix+"0000")+i));
                    }
                }
                rangeList.add(isbnList12.get(isbnList12.size()-1));
            }
            //移除数据库有的isbn
            for (int i=0;i<isbnList12.size();i++) {
                String isbn12=isbnList12.get(i);
                for (BookMenu bookMenu1 : bookMenuList1) {
                    if(isbn12.equals(bookMenu1.getIsbn().substring(0,bookMenu1.getIsbn().length()-1))){
                        isbnList12.remove(i);
                        i--;
                        break;
                    }
                }
            }
            //isbn12位转13位
            List<String> isbnList = isbnList12.stream().map(isbn12 -> isbn12 + calculateIsbnCheckDigit(isbn12)).toList();
            List<BookMenu> bookMenuList2=new ArrayList<>();
            int n=0;
            for (String isbn : isbnList) {
                BookMenu bookMenu1=new BookMenu();
                bookMenu1.setIsbn(isbn);
                if(n<rangeList.size()){
                    bookMenu1.setPublisher(rangeList.get(n));
                    n++;
                }
                bookMenuList2.add(bookMenu1);
            }
            if(bookMenuList2.isEmpty()){
                System.out.println(bookMenu.getPublisher()+"：没有待查数据");
                continue;
            }
            System.out.println(bookMenu.getPublisher()+"："+requireMap.size()+"个号段");
            ExcelUtils.writeExcel(originalPath.substring(0,originalPath.lastIndexOf('/')+1)+"五位数/待查/"+bookMenu.getPublisher()+"-待查.xlsx"
                    ,bookMenuList2, BookMenu.class);
        }
        return "成功";
    }

    @Override
    public String findLabelByAuthorPublisher(String dirPath) {
        File dir = new File(dirPath);
        if(!dir.exists()){
            return "目录不存在";
        }
        File[] files = dir.listFiles();
        labelList = labelMapper.selectByIdRange(1L, 500L);
        for (File file : files) {
            String path = file.getAbsolutePath().replace("\\", "/");
            List<BookTanshu> bookTanshuList = ExcelUtils.readExcel(path, BookTanshu.class);
            Map<String,String> map = new HashMap<>();
            for (BookTanshu bookTanshu : bookTanshuList) {
                if(bookTanshu.getLabel()!=null){
                    continue;
                }
                String author = bookTanshu.getAuthor();
                if(author ==null|| author.isEmpty()){
                    continue;
                }
                //先从缓存中取
                String cacheLabel = map.get(author);
                if(cacheLabel!=null){
                    bookTanshu.setLabel(cacheLabel);
                    continue;
                }
                String label = findLabelByAuthorPublisher(author,bookTanshu.getPublisher());
                if(label==null){
                    map.put(author,"");
                    continue;
                }
                map.put(author,label);
                bookTanshu.setLabel(label);
            }
            String directory = path.substring(0, path.lastIndexOf("/"));
            String fileName = path.substring(path.lastIndexOf("/") + 1);
            ExcelUtils.writeExcel(directory.substring(0,directory.lastIndexOf("/")+1)+"填标签/"+fileName,bookTanshuList, BookTanshu.class);
        }
        return "成功";
    }

    private String findLabelByAuthorPublisher(String author, String publisher) {
        if(author==null){
            return null;
        }
        List<Author> authorList = authorMapper.selectByAuthorRevContain(author);
        if(authorList==null||authorList.isEmpty()){
            System.out.println(author+" "+publisher+" 没查到作者数据");
            return null;
        }
        //找作者最长的长度（最接近给的作者）
        int length=0;
        for (Author au : authorList) {
            String author1 = au.getAuthor();
            if(author1==null||author1.isEmpty()){
                continue;
            }
            if(author1.length()>length){
                length=author1.length();
            }
        }
        List<Author> authorList1 = new ArrayList<>();
        for (Author au : authorList) {
            String author1 = au.getAuthor();
            if(author1==null||author1.isEmpty()){
                continue;
            }
            if(author1.length()==length){
                authorList1.add(au);
            }
        }
        if(authorList1.isEmpty()){
            return null;
        }
        List<Long> authorIdList = authorList1.stream().map(au -> au.getId()).collect(Collectors.toList());
        List<BookMenu> bookMenuList1 = bookMenuMapper.selectByAuthorIdsAndPublisherPrefix(authorIdList, null);
        if(bookMenuList1==null||bookMenuList1.isEmpty()){
            System.out.println(author+" "+publisher+" 没查到书目数据");
            return null;
        }
        //看标签是否相同
        String typeSame1 = isTypeSame(bookMenuList1);
        if(!"0".equals(typeSame1)){
            return typeSame1;
        }
        //进一步通过出版社筛选
        List<BookMenu> bookMenuList2 = new ArrayList<>();
        List<BookMenu> bookMenuList3 = new ArrayList<>();
        if(publisher!=null){
            for (BookMenu bookMenu : bookMenuList1) {
                String publisher1 = bookMenu.getPublisher();
                if(publisher1==null||publisher1.isEmpty()||bookMenu.getType()==null||bookMenu.getType().isEmpty()){ //避免通过出版社筛选得到type全是null的
                    continue;
                }
                if(publisher.startsWith(publisher1)||publisher1.startsWith(publisher)){
                    bookMenuList2.add(bookMenu);
                }
                if(publisher.contains(publisher1)||publisher1.contains(publisher)){
                    bookMenuList3.add(bookMenu);
                }
            }
        }
        if(!bookMenuList2.isEmpty()){ //优先使用出版社开头的
            String typeSame2 = isTypeSame(bookMenuList2);
            if(!"0".equals(typeSame2)){
                return typeSame2;
            }
            bookMenuList1=bookMenuList2;
        }else if(!bookMenuList3.isEmpty()){ //其次使用出版社包含的
            String typeSame2 = isTypeSame(bookMenuList3);
            if(!"0".equals(typeSame2)){
                return typeSame2;
            }
            bookMenuList1=bookMenuList3;
        }
        String firstType=null;
        int n=0;
        for (BookMenu bookMenu : bookMenuList1) { //最后使用没过滤的
            String type = bookMenu.getType();
            if(type==null||type.isEmpty()){
                continue;
            }
            if(n==0){
                firstType=type;
                n=1;
            }
            for (Label label : labelList) {
                String labelName = label.getLabelName();
                if(labelName==null||labelName.isEmpty()){
                    continue;
                }
                if(type.equals(labelName)){
                    return type;
                }
            }
        }
        return firstType;
    }

    private String isTypeSame(List<BookMenu> bookMenuList){
        String type=null;
        int n=0;
        for (BookMenu bookMenu : bookMenuList) {
            if(bookMenu.getType()==null||bookMenu.getType().isEmpty()){
                continue;
            }
            if(type==null){
                type=bookMenu.getType();
                continue;
            }
            if(!type.equals(bookMenu.getType())){
                n=1;
                break;
            }
        }
        if(n==0){
            return type;
        }
        return "0";
    }

    private String calculateIsbnCheckDigit(String isbn12) {
        int sum=0;
        for (int i = 0; i < 12; i++) {
            if((i+1)%2!=0){
                sum+=isbn12.charAt(i)-'0';
            }else {
                sum+=(isbn12.charAt(i)-'0')*3;
            }
        }
        return String.valueOf((10-sum%10) == 10 ? 0 : (10-sum%10));
    }
}
